import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:getxdemo/http/http_exception.dart';
import 'package:getxdemo/http/request_api.dart';
import 'package:connectivity/connectivity.dart';

/// 链接超时时间
const int _connectTimeout = 10000;
/// 请求超时时间
const int _requestTimeout = 10000;
/// 接收超时时间
const int _receivedTimeout = 10000;

typedef Success<T> = Function(T data);
typedef Fail = Function(int code, String message);

class HttpRequest{
  static Dio? _dio;

  static Dio instance([ bool isJson = false]){
    if(_dio == null){
      var options = BaseOptions(
        contentType: contentType(isJson),
        validateStatus: (status)=> true,
        baseUrl: RequestApi.baseurl,
        sendTimeout: _requestTimeout,
        connectTimeout: _connectTimeout,
        receiveTimeout: _receivedTimeout
      );
      _dio = Dio(options);
    }else{
      _dio?.options.contentType =contentType(isJson);
    }
    return _dio!;
  }

  static String contentType([bool isJson = true]){
    return isJson?Headers.jsonContentType:Headers.formUrlEncodedContentType;
  }

  static Future<void> request<T>(Method method,String path,dynamic params,{
    bool isJson = false,
    Success? success,
    required Fail? fail,
  }) async {
    try {
      debugPrint("request data =>$params");
      ConnectivityResult connectivityResult = await Connectivity().checkConnectivity();
      if(connectivityResult == ConnectivityResult.none){
        _onError(HttpException.netError, "网络异常，请检查你的网络！", fail);
        return;
      }
      Response response = await instance(isJson).request(path,data: params,options: Options(
        method: methodValue[method],
        headers: _headerToken(),
      ));

      if(success != null){
        success(response.data);
      }

    } on DioError catch (e) {
      NetError err = HttpException.handleException(e);
      _onError(err.code, err.msg, fail);
      debugPrint("网络异常${e.message}");
    }
  }







}

/// 错误回调
/// [code] 错误代码
/// [msg] 错误信息
/// [fail] 错误回调
void _onError(int code, String msg, Fail? fail) {
  if (code == 0) {
    code = HttpException.unknownError;
    msg = '未知异常';
  }
  if (fail != null) {
    fail(code, msg);
  }
}

/// 请求时添加cookie
Map<String, dynamic>? _headerToken(){
  /// 自定义Header,如需要添加token信息请调用此参数
  Map<String, dynamic> httpHeaders = {
    // 'Cookie': 'loginUserName=${info.username};loginUserPassword=${info.password}',
  };
  return httpHeaders;
}


enum Method{GET,POST}

const methodValue = {
  Method.GET: "get",
  Method.POST: "post"
};
